<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="text" id='aa'>
    <button id='send'> 发送</button>
    <div id='aaa'></div>
</body>
<script>
    function showmessage(str, type) {
        let div = document.createElement('div')
        div.innerHTML = str
        if (type == 'enter') {
            div.style.color = 'blue'
        } else if (type == 'leave') {
            div.style.color = 'red'
        }
        else if (type == 'message') {
            div.style.color = 'green'
        }
        document.body.append(div)
    }
    var ws = new WebSocket("ws://localhost:3000/");// 设置服务器地址 //
    //创建连接
    ws.onopen = function () {
        document.getElementById('send').onclick = function () {
            let txt = document.getElementById('aa').value
            ws.send(txt);
        }
    }
    //关闭
    ws.onclose = function () {
        console.log("Connection closed.");
    }
    //接收信息
    ws.onmessage = function (e) {
        let mes = JSON.parse(e.data)
        console.log(e)
        showmessage(mes.data, mes.type)
    }
</script>

</html>